package com.monkeybrother.thread.atomic;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Desc
 * @Author houry
 * @Date 2021/1/22 11:09
 **/
public class AtomicStampedReferenceTest {

    private final static AtomicStampedReference<Integer> stamp = new AtomicStampedReference<>(100, 1);

    public static void main(String[] args) {
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " 第1次版本号:" + stamp.getStamp());
            stamp.compareAndSet(100, 200, stamp.getStamp(), stamp.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + " 第2次版本号:" + stamp.getStamp());
            stamp.compareAndSet(200, 100, stamp.getStamp(), stamp.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + " 第2次版本号:" + stamp.getStamp());
        }).start();

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + " 第1次版本号:" + stamp.getStamp());
                stamp.compareAndSet(100, 400, stamp.getStamp(), stamp.getStamp() + 1);
                System.out.println(Thread.currentThread().getName() + " 获取到的值：" + stamp.getReference());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}